<template>
  <div class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
             style="width: 100%; padding: 0 30px;">

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="单位名称" prop="name">
            <el-input maxlength="50" v-model="temp.name"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人代表" prop="mhLegalPerson">
            <el-input maxlength="50" v-model="temp.mhLegalPerson"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="登录账号" prop="loginname">
            <el-input maxlength="50" v-model="temp.loginname"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input placeholder="长度请大于6位小于15位" v-model="temp.password"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="mhLinkman">
            <el-input maxlength="50" v-model="temp.mhLinkman"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="mhPhone">
            <el-input v-model="temp.mhPhone"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织机构代码" prop="mhOrgCode">
            <el-input maxlength="50" v-model="temp.mhOrgCode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="mhEmail">
            <el-input maxlength="50" v-model="temp.mhEmail"/>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="上传社会信用统一代码证" label-width="190px" prop="mhBizLicenseSignpic">
            <!--<el-input v-model="temp.bizLicenseSignpic" type="hidden"/>-->
            <el-upload
              ref="licenseSignpicUpload"
              action="string"
              accept="image/*"
              :limit="imgLimit"
              :file-list="licenseSignpicImgs"
              :multiple="licenseSignpicIsMultiple"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemoveLicenseSignpic"
              :on-exceed="handLeExceed"
              :auto-upload="true"
              :before-upload="beforeUpload"
              :http-request="licenseSignpicUpload">
              <i class="el-icon-plus" style="line-height: 100px;width: 100px;height: 100px;"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" append-to-body width="70%">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <span style="text-align:right;color: red;">{{result}}<font color='grey' size="15">{{total}}</font>{{totalContent}}</span>
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  import { createApi, fetchList, uploadImg, register } from './api'
  // 导入多选项组件
  import SelectOption from '@/views/coding/components/SelectOption'

  export default {
    name: 'Unit-MhUnit-FormDetail',

    components: { SelectOption },

    props: {
      isModule: {
        type: Boolean,
        default: false
      },
      row: {}
    },

    data() {
      var checkMobile = (rule, value, cb) => {
        const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
        if (regMobile.test(value)) {
          return cb()
        }
        cb(new Error('只能输入11位手机号'))
      }
      return {
        rules: {
          mhLegalPerson: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
          mhBizLicenseSignpic: [{ required: true, message: '请上传社会信用统一代码证', trigger: 'blur' }],
          mhOrgCode:[{ required: true, message: '请输入组织机构代码', trigger: 'blur' }],
          name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
          loginname: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
          password: [{ required: true, message: '请输入密码', trigger: 'blur' }, {
            min: 6, max: 15, message: '长度在6~15个字符', trigger: 'blur'
          }],
          mhLinkman: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
          mhEmail: [{ required: true, message: '请输入邮箱', trigger: 'blur' },{ type: 'string',
            message: '邮箱格式不正确',
            trigger: 'blur',
            transform (value) {
              if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)) {
                return true
              }else{
              }
            }
          }

          ],
          mhPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, {
            validator: checkMobile,
            trigger: 'blur'
          }]
        },
        total: undefined,   //记录具体倒计时时间
        clock: undefined,
        totalContent: '',
        dialogVisible: false,
        dialogImageUrl: '',
        licenseSignpicImgs: [],
        licenseSignpicIsMultiple: false,
        imgLimit: 1,//上传文件个数限制
        temp: {},
        licenseSignpicArr: [],
        result: ''
      }
    },

    watch: {
      'row': {
        immediate: true, // vue首次赋值不触发watch的解决方法
        handler: function(nval) {
          if (this.isModule) {
            // this.temp = Object.assign({}, this.row) // copy obj
            if (this.isNull(nval)) {
              return
            }
            if (this.isNull(nval.id)) {
              return
            }
            this.getList(nval.id)
          }
        }
      }
    },
    beforeDestroy() {
      if (this.clock) {
        clearInterval(this.clock)
      }
    },
    methods: {
      getList(_id) {
        this.resetTemp()
        fetchList({ id: _id }).then(result => {
          if (!result.success) {
            this.notify(result)
            return
          }
          this.temp = result.map.rows[0]
        })
      },
      // 给外部调用，清空form
      resetTemp() {
        this.temp = {
          legalPerson: '',
          // bizLicenseSignpic: '',
          mhBizLicenseSignpic:'',
          status: 2,
          name: '',
          account: '',
          password: '',
          linkman: '',
          telephone: '',
          deleteflag: '',
          id: undefined
        }
        this.licenseSignpicClearFiles()
      },
      // 给外部调用，设置默认值，请根据实际情况修改id值
      defaultTemp() {
        this.temp = {
          status: 2, //设置默认值
          deleteflag: 0 //设置默认值
        }
      },
      // 树表： 拿当前节点ID作为父节点ID，建立树关系
      setParentNodeId(id) {
        this.temp.parentId = id
      },
      // 给外部调用，插入记录
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const param = Object.assign({}, this.temp)
            createApi(param).then((r) => {
              this.notify(r)
              if (r.success) {
                this.resetTemp()
                // 从父组件调用此方法，进行回调下
                if (this.isModule) {
                  this.$emit('createResult')
                }
              }
            })
          }
        })
      },
      licenseSignpicUpload(params) {//上传社会信用统一代码证
        let formData = new FormData()
        formData.append('file', params.file)
        uploadImg(formData).then(res => {
          if (res.success) {
            params.file.url = res.map.url
            params.file.group = res.map.group
            this.licenseSignpicImgs.push(params.file)
            this.licenseSignpicArr.push(res.map.url)
            this.temp.bizLicenseSignpic = JSON.stringify(this.licenseSignpicArr)
          }
        })
      },
      handleRemoveLicenseSignpic(file, fileList) {//删除指定社会信用统一代码证
        this.licenseSignpicImgs.length = 0
        this.licenseSignpicArr.length = 0
        this.temp.bizLicenseSignpic = ''
        fileList.forEach((item, index) => {
          // console.log(item.raw.url);
          this.licenseSignpicImgs.push(item)
          this.licenseSignpicArr.push(item.url)
        })
      },
      licenseSignpicClearFiles() {//清除全部社会信用统一代码证
        this.$refs.licenseSignpicUpload.clearFiles()
        this.licenseSignpicImgs = []
        this.licenseSignpicArr = []
      },
      handlePictureCardPreview(file) {//点击文件列表中已上传的文件时的钩子
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },

      handLeExceed(files, fileList) {//文件超出个数限制时的钩子
        this.$notify({ title: '警告', type: 'warning', message: '当前只允许选择' + this.imgLimit + '张图片' })
        return false
      },
      beforeUpload(file) {
        //上传文件之前的钩子
        //验证图片大小
        const isLt5M = file.size > 1024 * 1024 //1M
        if (isLt5M) {
          this.$notify({ title: '警告', type: 'warning', message: '上传的图片大小不能超过1M' })
          return false
        }
      },
      // 给外部调用，清除校验
      clearValidate() {
        this.$refs['dataForm'].clearValidate()
      },
      // submit
      register() {
        this.result = ''
        // img url list: [], ["http://lll/11.jpg",""]

        //判断是否上传了
        if(this.licenseSignpicArr.length===0){
          this.result = '请上传社会信用统一代码证'
          return
        }
        this.temp.mhBizLicenseSignpic = JSON.stringify(this.licenseSignpicArr)
        //
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const param = Object.assign({}, this.temp)
            register(param).then(r => {
              if (r.success) {
                this.result = '注册完毕，请等待后台审核。'

                this.total = 5
                this.totalContent = '秒后自动关闭'
                this.clock = setInterval(() => {
                  if (this.total > 0) {
                    --this.total
                  }
                }, 1000)
                this.resetTemp()
                if (this.isModule) {
                  setTimeout(() => {
                    this.$emit('createResult')
                  }, 5000)
                }
              } else {
                this.result = r.content
              }
            })
          }
        })
      }

    }
  }
</script>
<style>

</style>
